package com.lxw.nonghe.util;

import cn.dev33.satoken.stp.StpUtil;
import com.lxw.nonghe.entity.OperationLog;
import com.lxw.nonghe.entity.User;
import com.lxw.nonghe.service.OperationLogService;
import com.lxw.nonghe.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RequiredArgsConstructor
public class LogUtils {
    private final OperationLogService operationLogService;
    private final UserService userService; // 添加UserService依赖

    public void recordLog(String module, String operation, String status, String errorMsg) {
        OperationLog log = new OperationLog();

        // 直接从Sa-Token获取当前登录用户信息
        if (StpUtil.isLogin()) {
            long userId = StpUtil.getLoginIdAsLong();
            log.setUserId((int) userId);

            // 从数据库获取用户名（避免缓存一致性问题）
            User user = userService.getById(userId);
            if (user != null) {
                log.setUsername(user.getUsername());
            }
        }

        log.setModule(module);
        log.setOperation(operation);
        log.setStatus(status);
        log.setErrorMsg(errorMsg);
        log.setOperationTime(new Date());

        operationLogService.saveLog(log);
    }
}
